
package com.kugou.game.sdk.service;

import com.kugou.framework.base.BaseService;
import com.kugou.game.sdk.entity.MessageHttpResponse;
import com.kugou.game.sdk.entity.MessageInfo;
import com.kugou.game.sdk.persistence.preference.PrefUtil;
import com.kugou.game.sdk.protocol.MessageTask;
import com.kugou.game.sdk.receiver.PowerReceiver;
import com.kugou.game.sdk.receiver.PushMessageReceiver;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.PushFileUtil;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

public class MessageService extends BaseService {
    /** 可以处理的最新的消息类型 */
    public static final int MESSAGE_TYPE = 4;

    public static final String INTENT_MESSAGE_SDK_DATA = "message_sdk_data";

    public static final String INTENT_MESSAGE_TYPE = "message_type";

    // MessageInfo 对应的json字符串
    public static final String INTENT_MESSAGE_INFO_MOREEXTRA = "message_info_moreextra";

    /** 应用包名 */
    public static final String INTENT_PACKAGENAME = "package_name";

    /** 消息配置 */
    public static final String INTENT_MESSAGE_CONFIG = "messgae_config";

    final static int LONG_FREQUENCY = 60 * 60 * 1000;

    final static long SHORT_FREQUENCY = 60 * 1000;

    static long DELAY = SHORT_FREQUENCY;// 间隔时间 单位s

    String mMesVersionId = "0";

    List<MessageInfo> mMessageList;

    HashMap<String, Object> mPackageMap;

    // 消息列表的json字符串
    List<String> mMessageJsonList;

    // 定时器
    Timer mTimer;

    // 是否正在处理消息
    boolean mIsHandling = false;

    MyHandler mHandler;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 定时任务
    MyTimerTask mTask;

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            // 如果上一次拉取的消息还没处理完毕，则先不进行消息拉取
            if (mIsHandling)
                return;
            // 获取服务器message
            MessageHttpResponse mr = new MessageTask().request(MessageService.this, mAppid,
                    mAppkey, mGameid, mMerchantId, mSdkversioncode, mSdkversionname, mGametype,
                    mMesVersionId);
            if (mr != null) {
                mIsHandling = true;
                mMessageList.clear();
                mMessageJsonList = mr.getMessageInfoListJson();
                // 缓存到本地
                if (!TextUtils.isEmpty(mr.getMesVersionId())) {
                    mMesVersionId = mr.getMesVersionId();
                    PrefUtil.setMessageVersion(getApplicationContext(), mMesVersionId);
                }
                if (mr.getMessageInfoList() != null && mr.getMessageInfoList().size() > 0) {
                    mMessageList.addAll(mr.getMessageInfoList());
                }
                mHandler.sendEmptyMessage(0);
            }
        }

    }

    static class MyHandler extends Handler {

        WeakReference<MessageService> wr;

        public MyHandler(MessageService ms) {
            wr = new WeakReference<MessageService>(ms);
        }

        public void handleMessage(android.os.Message msg) {
            MessageService ms = wr.get();
            if (ms != null) {
                // 如果当前显示消息的包名列表为空,都不显示消息
                if (ms.mPackageMap.isEmpty()) {
                    ms.mIsHandling = false;
                    // 当前应用不显示消息
                    return;
                }
                int i = 0;
                for (MessageInfo info : ms.mMessageList) {
                    Iterator<Entry<String, Object>> iter = ms.mPackageMap.entrySet().iterator();
                    Entry<String, Object> entry;
                    // 记录是第几条message
                    while (iter.hasNext()) {
                        entry = iter.next();
                        // 只有当能处理的消息类型高于当前的消息的类型,并且对应的应用已经安装时，才发送定向广播
                        if ((Integer.parseInt((String) entry.getValue()) >= Integer.parseInt(info
                                .getType())) && ms.isAvilible(ms, entry.getKey())) {
                            Intent intent = new Intent(
                                    PushMessageReceiver.ACTION_RECEIVE_PUSHMESSAGE);
                            intent.setPackage(entry.getKey());
                            ms.putMoreExtra(intent, ms.mMessageJsonList.get(i));
                            ms.sendBroadcast(intent);
                            break;
                        }
                    }
                    i++;
                }
                ms.mIsHandling = false;
            }
        }
    }

    // 检查应用是否已经安装
    private boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for (int i = 0; i < pinfo.size(); i++) {
            if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
                return true;
        }
        return false;
    }

    /**
     * 将MessageInfo里的字段分别加到intent中
     * 
     * @param intent
     * @param mInfo
     */
    private void putMoreExtra(Intent intent, String str) {
        intent.putExtra(INTENT_MESSAGE_INFO_MOREEXTRA, str);
    }

    @Override
    public void onCreate() {
        // 注册屏幕亮灭广播
        registerReceiver();
        mPackageMap = new HashMap<String, Object>();
        mHandler = new MyHandler(this);
        mMessageList = new ArrayList<MessageInfo>();
        mTask = new MyTimerTask();
        mTimer = new Timer(true);
        // 读取本地版本号
        mMesVersionId = PrefUtil.getMessageVersion(this);
        // 读取本地缓存的不显示的那些包
        readFile();
        mTimer.schedule(mTask, 50, DELAY);
    }

    // 解析本地缓存的json数据
    @SuppressWarnings("unchecked")
    private void readFile() {
        String res = PushFileUtil.read(getApplicationContext());
        if (!TextUtils.isEmpty(res)) {
            try {
                JSONObject jObj = new JSONObject(res);
                Iterator<String> iter = jObj.keys();
                if (iter != null) {
                    String key = null;
                    while (iter.hasNext()) {
                        key = iter.next();
                        mPackageMap.put(key, jObj.get(key));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        unregisterReceiver();
        mHandler.removeCallbacksAndMessages(null);
        mTimer.cancel();
        Intent intent = new Intent(PowerReceiver.ACTION_SERVICE_DESTORY);
        sendBroadcast(intent);
    }

    void saveToFile() {
        String str = AppUtil.convertHashMapToJson(mPackageMap);
        PushFileUtil.write(getApplicationContext(), str);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String mPackage_name = intent.getStringExtra(INTENT_PACKAGENAME);
        int message_config = intent.getIntExtra(INTENT_MESSAGE_CONFIG, 0);
        int intent_msgtype = intent.getIntExtra(INTENT_MESSAGE_TYPE, 0);
        String sdk_config_data = intent.getStringExtra(INTENT_MESSAGE_SDK_DATA);
        // 解析SDK的配置参数，用于网络接口
        handSdkConfigData(sdk_config_data);
        if (!TextUtils.isEmpty(mPackage_name)) {// 当前应用显示消息
            // 缓存当前显示消息的包名到本地
            if (message_config == 1) {
                mPackageMap.put(mPackage_name, intent_msgtype + "");
            } else {
                mPackageMap.remove(mPackage_name);
            }
            saveToFile();
        }
        return START_REDELIVER_INTENT;
    }

    private int mGameid, mMerchantId, mSdkversioncode, mGametype;

    private String mAppkey, mSdkversionname;

    private long mAppid;

    private void handSdkConfigData(String config) {
        if (TextUtils.isEmpty(config)) {
            return;
        }
        try {
            JSONObject obj = new JSONObject(config);
            mAppid = obj.optLong("appid");
            mAppkey = obj.optString("appkey");
            mGameid = obj.optInt("gameid");
            mMerchantId = obj.optInt("merchantid");
            mSdkversioncode = obj.optInt("sdkversioncode");
            mSdkversionname = obj.optString("sdkversionname");
            mGametype = obj.optInt("gametype");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        // 灭屏动作
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 亮屏动作
        filter.addAction(Intent.ACTION_SCREEN_ON);
        MessageService.this.registerReceiver(mReceiver, filter);
    }

    private void unregisterReceiver() {
        if (mReceiver != null) {
            MessageService.this.unregisterReceiver(mReceiver);
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null)
                return;
            if (action.equals(Intent.ACTION_SCREEN_ON)) {
                // 更改定时器频率
                changePeriod(SHORT_FREQUENCY);
            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                // 更改定时器频率
                changePeriod(LONG_FREQUENCY);
            }
        }
    };

    // 更改轮询频率
    private void changePeriod(long period) {
        if (mTimer != null) {
            DELAY = period;
            mTimer.cancel();
            mTimer.purge();
            mTimer = new Timer(true);
            mTask = new MyTimerTask();
            mTimer.schedule(mTask, 0, DELAY);
        }
    }
}
